﻿// ******************************************************************
// * Copyright(c)  Steven Lu
// * Description   : Entity_INV_RETURN_IMPORT_ORDER
// * CreateDate    : 2013/1/16 20:27:30
// * Creater       : InvReturnImportOrderBs
// * LastChangeDate: 2013/1/16 20:27:30
// * LastChanger   : 2013/1/16 20:27:30
// * Version Info  : 1.0 For ESOL
// ******************************************************************

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Suzsoft.Smart.Data;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Common;

namespace ESOL.Business.Inv
{
    /// <summary>
    /// InvReturnImportOrder
    /// </summary>
    public partial class InvReturnImportOrderBs
    {
        #region GetByID
        /// <summary>
        /// Get Entity
        /// </summary>
        /// <param name="objInvReturnImportOrderEntity">Entity</param>
        /// <returns>Entity</returns>
        public static InvReturnImportOrderEntity GetInvReturnImportOrder(InvReturnImportOrderEntity objInvReturnImportOrderEntity)
        {
            return DataAccess.SelectSingle<InvReturnImportOrderEntity>(objInvReturnImportOrderEntity);
        }
        #endregion


        #region Insert
        /// <summary>
        /// Insert Data
        /// </summary>
        /// <param name="objInvReturnImportOrderEntity">Entity</param>
        /// <returns>true Insert Succeed; false Insert Fail</returns>
        public static bool InsertInvReturnImportOrder(InvReturnImportOrderEntity objInvReturnImportOrderEntity)
        {
            return DataAccess.Insert(objInvReturnImportOrderEntity);
        }

        public static bool InsertInvReturnImportOrder(List<InvReturnImportOrderEntity> objInvReturnImportOrderEntityList)
        {
            return DataAccess.Insert(objInvReturnImportOrderEntityList);
        }
        #endregion


        #region Update
        /// <summary>
        /// Update Data
        /// </summary>
        /// <param name="objInvReturnImportOrderEntity">Entity</param>
        /// <returns>true Update Succeed; false Update Fail</returns>
        public static bool UpdateInvReturnImportOrder(InvReturnImportOrderEntity objInvReturnImportOrderEntity)
        {
            return DataAccess.Update(objInvReturnImportOrderEntity);
        }

        public static bool UpdateInvReturnImportOrder(List<InvReturnImportOrderEntity> objInvReturnImportOrderEntityList)
        {
            return DataAccess.Update<InvReturnImportOrderEntity>(objInvReturnImportOrderEntityList);
        }
        #endregion


        #region Delete
        /// <summary>
        /// Delete Data
        /// </summary>
        /// <param name="objInvReturnImportOrderEntity">Entity</param>
        /// <returns>true Delete Succeed; false Delete Fail</returns>
        public static bool DeleteInvReturnImportOrder(InvReturnImportOrderEntity objInvReturnImportOrderEntity)
        {
            return DataAccess.Delete(objInvReturnImportOrderEntity);
        }

        public static bool DeleteInvReturnImportOrder(List<InvReturnImportOrderEntity> objInvReturnImportOrderEntityList)
        {
            return DataAccess.Delete<InvReturnImportOrderEntity>(objInvReturnImportOrderEntityList);
        }
        #endregion


        #region GetAll
        /// <summary>
        /// Get All Data
        /// </summary>
        /// <returns>Back All Data<returns>
        public static DataSet GetInvReturnImportOrderAll()
        {
            return DataAccess.SelectAllDataSet<InvReturnImportOrderEntity>();
        }
        /// <summary>
        /// Get All Data List
        /// </summary>
        /// <returns>Back All Data List<returns>
        public static List<InvReturnImportOrderEntity> GetInvReturnImportOrderAllList()
        {
            return DataAccess.SelectAll<InvReturnImportOrderEntity>();
        }
        #endregion

        public static DataTable GetByConditon(string condition,string orderBy,string RowCount)
        {
            string sql = CommonFunctions.GetSelect(RowCount) + @" A.*,B.ORDER_CODE AS RETURN_ORDER_CODE,C.NAME_CN FROM dbo.INV_RETURN_IMPORT_ORDER A
                           LEFT JOIN dbo.SALES_RETURN_ORDER B ON A.RETURN_ORDER_ID=B.ID
                           LEFT JOIN dbo.MST_PERSON C ON A.CREATED_BY=C.PERSON_ID
                           WHERE 1=1 ";
            if (string.IsNullOrEmpty(condition) == false)
            {
                sql += condition;
            }
            if (string.IsNullOrEmpty(orderBy) == false)
            {
                sql += " ORDER BY " + orderBy;
            }
            DataSet ds = DataAccess.SelectDataSet(sql);
            if (ds != null && ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            return null;
        }
        public static bool CreateReturnImportOrder(InvReturnImportOrderEntity entity,DataTable dtItems,bool isNew, string msg)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();
                    if (isNew)
                    {
                        string code = "";
                        if (MstCodeRuleBs.GetCurrentOrderCode("InvReturnImportOrderCode", out code, broker) == false)
                        {
                            broker.RollBack();
                            throw new Exception("自动生成发货申请单号失败！");
                        }
                        entity.OrderCode = code;
                        DataAccess.Insert(entity, broker);
                    }
                    else
                    {
                        DataAccess.Update(entity, broker);

                    }

                    //Save items

                    List<InvReturnImportItemEntity> insertList = new List<InvReturnImportItemEntity>();
                    List<InvReturnImportItemEntity> modifyList = new List<InvReturnImportItemEntity>();
                    foreach (DataRow dr in dtItems.Rows)
                    {
                        InvReturnImportItemEntity Item = null;
                        switch (dr.RowState)
                        {
                            case DataRowState.Added:
                                Item = new InvReturnImportItemEntity(dr);
                                if (string.IsNullOrEmpty(Item.ProductId))
                                {
                                    Item.ProductId = null;
                                }
                                Item.InvReturnImportOrderId = entity.Id;
                                insertList.Add(Item);
                                break;
                            case DataRowState.Modified:
                                Item = new InvReturnImportItemEntity(dr);
                                if (string.IsNullOrEmpty(Item.ProductId))
                                {
                                    Item.ProductId = null;
                                }
                                Item.InvReturnImportOrderId = entity.Id;
                                modifyList.Add(Item);
                                break;
                            default:
                                continue;
                        }
                    }
                    //DataAccess.Delete<SalesReturnItemEntity>(deleteSalesReturnItems, broker);
                    DataAccess.Update<InvReturnImportItemEntity>(modifyList, broker);
                    DataAccess.Insert<InvReturnImportItemEntity>(insertList, broker);

                    //Send message
                    MstMessageEntity message = new MstMessageEntity();
                    message.MessageId = Guid.NewGuid().ToString();
                    message.MessateTitle = "审核退货入库单";
                    message.MessageBody = @"请审核一下退货入库单
申请单号：" + entity.OrderCode + @"；
申请日期：" + entity.Created.ToString("yyyy-MM-dd");
                    message.MessageDate = DateTime.Now;
                    message.MessageSender = entity.CreatedBy;
                    message.MessageLevel = "ML03";
                    message.FormName = "ESOL.WinUI.Inv.frmManageReturnImportOrder";
                    MstMessageBs.SendApproveMessage(message, "ESOL.WinUI.Inv.frmManageReturnImportOrder", "btnApprove", broker);

                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
                return false;
            }
        }

        public static bool ApproveReturnImportOrder(InvReturnImportOrderEntity Entity, DataTable dtItems, string msg)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();
                    //更新主单
                    DataAccess.Update(Entity, broker);

                    //更新库存表
                    List<InvStorageEntity> listStorage = new List<InvStorageEntity>();
                    foreach (DataRow dr in dtItems.Rows)
                    {
                        InvReturnImportItemEntity entity = new InvReturnImportItemEntity(dr);
                        InvStorageEntity storage = new InvStorageEntity();
                        InvStorageChangeEntity entityStroageChange = new InvStorageChangeEntity();

                        //更新入库明细
                        DataAccess.Update(entity, broker);

                        //更新 StorageChange 表
                        entityStroageChange.ChangeId = Guid.NewGuid().ToString();
                        entityStroageChange.ChangeQty = Convert.ToDecimal(entity.ImportQty);
                        entityStroageChange.ChangeTime = DateTime.Now;
                        entityStroageChange.ChangeUser = Common.CommonParameter.CurrentUser.PersonId;//InvImportOrderBs.GetInvImportOrderByID(entity.ImportOrderId).ApprovedBy;
                        entityStroageChange.ProductId = entity.ProductId;
                        entityStroageChange.RelatedOrder = entity.InvReturnImportOrderId;
                        entityStroageChange.LocationId = entity.MstLocationId;
                        //entityStroageChange.Remark = entity.Remark;
                        entityStroageChange.ChangeType = "INVC02";
                        DataAccess.Insert(entityStroageChange, broker);

                        string sql = @"SELECT * FROM INV_STORAGE WHERE PRODUCT_ID='"+entity.ProductId+"' AND LOCATION_ID='"+entity.MstLocationId+"'";
                        DataSet ds = DataAccess.SelectDataSet(sql);
                        if (ds != null && ds.Tables[0].Rows.Count != 0)
                        {
                            decimal New_QTY = Convert.ToDecimal(ds.Tables[0].Rows[0]["current_qty"]) + Convert.ToDecimal(entity.ImportQty);
                            string sql2 = @"UPDATE INV_STORAGE SET CURRENT_QTY='" + New_QTY + "' WHERE PRODUCT_ID='" + entity.ProductId + "' AND LOCATION_ID='" + entity.MstLocationId + "'";
                            broker.ExecuteSQL(sql2);
                        }
                        else
                        {
                            InvStorageEntity entityStroage = new InvStorageEntity();
                            entityStroage.ProductId = entity.ProductId;
                            entityStroage.LocationId = entity.MstLocationId;
                            entityStroage.CurrentQty = Convert.ToDecimal(entity.ImportQty);
                            entityStroage.FixedQty = 0;
                            entityStroage.LastRelatedOrder = entity.InvReturnImportOrderId;
                            entityStroage.LastUpdateDate = DateTime.Now;
                            entityStroage.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;//InvImportOrderBs.GetInvImportOrderByID(entity.ImportOrderId).ApprovedBy;
                            DataAccess.Insert(entityStroage, broker);
                        }
                    }

                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
        }
    }


}

